<template>
  <view class="bg-gray-50 min-h-screen w-[750rpx] box-border bgs">
    <!-- Header -->
    <PageHeader title="" :showBack="true" :onlyBack="true" />
    <view
      class="bg-gradient-to-r sticky top-0 z-[2] from-blue-600 to-purple-600 text-white p-[40rpx] text-center relative overflow-hidden"
    >
      <view
        class="absolute w-[300rpx] h-[300rpx] bg-white bg-opacity-10 rounded-full -top-[100rpx] -right-[80rpx]"
      >
      </view>
      <view
        class="absolute w-[200rpx] h-[200rpx] bg-white bg-opacity-8 rounded-full -bottom-[80rpx] -left-[60rpx]"
      >
      </view>

      <text class="text-[42rpx] font-bold mb-[10rpx] block relative z-2"
        >成为平台商家</text
      >
      <text class="text-[26rpx] opacity-90 relative z-2"
        >开启您的商业之旅，共享平台资源</text
      >
    </view>

    <view class="p-[50rpx]">
      <!-- 商家类型选择 -->
      <view
        class="bg-white rounded-[20rpx] p-[30rpx] shadow-lg mb-[50rpx] border border-gray-100"
      >
        <view
          class="text-[32rpx] text-blue-600 mb-[30rpx] pb-[15rpx] border-b-2 border-blue-50 flex items-center"
        >
          <view
            class="w-[50rpx] h-[50rpx] bg-blue-50 rounded-full flex items-center justify-center mr-[15rpx]"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="shangjia"
              size="20"
              color="#4a6bff"
            />
          </view>
          <text>选择商家类型</text>
        </view>

        <view class="flex flex-wrap gap-[30rpx]">
          <view
            v-for="(type, index) in merchantTypes"
            :key="index"
            class="flex-1 min-w-[200rpx] border-2 rounded-[20rpx] p-[30rpx] text-center cursor-pointer transition-all relative overflow-hidden"
            :class="
              selectedType === type.value
                ? 'border-blue-600 bg-blue-50'
                : 'border-gray-200 bg-gray-50'
            "
            @click="selectType(type.value)"
          >
            <view
              v-if="selectedType === type.value"
              class="absolute top-[10rpx] right-[10rpx] w-[30rpx] h-[30rpx] bg-blue-600 text-white rounded-full flex items-center justify-center text-[20rpx]"
            >
              ✓
            </view>
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              :name="type.icon"
              size="30"
              color="#4a6bff"
            />
            <text class="text-[32rpx] font-semibold mb-[10rpx] block">{{
              type.name
            }}</text>
            <text class="text-[24rpx] text-gray-600">{{ type.desc }}</text>
          </view>
        </view>
      </view>

      <!-- 商家信息 -->
      <view
        class="bg-white rounded-[20rpx] p-[30rpx] shadow-lg mb-[50rpx] border border-gray-100"
      >
        <view
          class="text-[32rpx] text-blue-600 mb-[30rpx] pb-[15rpx] border-b-2 border-blue-50 flex items-center"
        >
          <view
            class="w-[50rpx] h-[50rpx] bg-blue-50 rounded-full flex items-center justify-center mr-[15rpx]"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="xinxiinfo21"
              size="20"
              color="#4a6bff"
            />
          </view>
          <text>商家信息</text>
        </view>

        <nut-form ref="formRef" :model="formData">
          <!-- 选择行业 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              选择行业 <text class="text-red-500">*</text>
            </text>
            <view
              class="w-full p-[25rpx] text-[26rpx] border-2 border-gray-200 rounded-[15rpx] bg-gray-50"
              @click="showIndustryPicker = true"
            >
              {{ industryText || "请选择所属行业（可多选）" }}
            </view>

            <nut-popup
              v-model:visible="showIndustryPicker"
              position="bottom"
              round
            >
              <view class="bg-white p-[40rpx] max-h-[70vh] overflow-auto">
                <view class="text-[32rpx] font-bold mb-[30rpx] text-center"
                  >选择行业（可多选）</view
                >

                <view class="space-y-[20rpx]">
                  <view
                    v-for="item in industryOptions"
                    :key="item.value"
                    class="flex items-center p-[20rpx] border-b border-gray-100"
                    @click="toggleIndustry(item.value)"
                  >
                    <nut-checkbox
                      :model-value="selectedIndustries.includes(item.value)"
                      class="mr-[20rpx]"
                    />
                    <text class="text-[28rpx]">{{ item.text }}</text>
                  </view>
                </view>

                <nut-button
                  type="primary"
                  class="mt-[40rpx] w-full"
                  @click="onIndustryConfirm"
                >
                  确认选择
                </nut-button>
              </view>
            </nut-popup>
          </view>

          <!-- 服务范围 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              服务范围 <text class="text-red-500">*</text>
            </text>
            <nut-textarea
              v-model="formData.serviceScope"
              placeholder="请详细描述您的服务范围、服务区域及服务内容"
              class="w-full !p-2 !h-[200rpx] box-border border-solid !border-2 !border-gray-500 !rounded-[12rpx] !bg-gray-50"
              maxlength="500"
            />
          </view>

          <!-- 上传营业执照 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              上传营业执照 <text class="text-red-500">*</text>
            </text>
            <view
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
              :class="
                uploadedLicense
                  ? 'border-blue-600 bg-blue-50'
                  : 'hover:border-blue-600 hover:bg-blue-50'
              "
              v-if="!uploadedLicense"
              @click="uploadLicense"
            >
              <IconFont
                font-class-name="iconfont"
                class-prefix="icon"
                :name="uploadedLicense ? 'file-image' : 'tubiao-yunshangchuan'"
                class="text-[50rpx] mb-[20rpx]"
                :class="uploadedLicense ? 'text-green-500' : 'text-blue-600'"
                size="40"
                color="#4a6bff"
              />
              <text class="text-[26rpx] text-gray-600 block">
                {{ uploadedLicense ? "营业执照已上传" : "点击上传营业执照" }}
              </text>
              <text class="text-[22rpx] text-gray-500 mt-[15rpx] block">
                {{
                  uploadedLicense
                    ? "点击可重新上传"
                    : "支持 JPG、PNG 格式，大小不超过 5MB"
                }}
              </text>
            </view>
            <!-- 显示营业执照图片 -->
            <view
              v-else="uploadedLicense"
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
            >
              <img :src="getFullPath(formData.businessPic)" />
            </view>
          </view>

          <!-- 上传正面身份证 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              上传正面身份证 <text class="text-red-500">*</text>
            </text>
            <view
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
              :class="
                uploadedFrontCard
                  ? 'border-blue-600 bg-blue-50'
                  : 'hover:border-blue-600 hover:bg-blue-50'
              "
              v-if="!uploadedFrontCard"
              @click="uploadIdCard('front')"
            >
              <IconFont
                font-class-name="iconfont"
                class-prefix="icon"
                :name="
                  uploadedFrontCard ? 'file-image' : 'shenfenzhengzhengmian'
                "
                class="text-[50rpx] mb-[20rpx]"
                :class="uploadedFrontCard ? 'text-green-500' : 'text-blue-600'"
                size="50"
                color="#4a6bff"
              />
              <text class="text-[26rpx] text-gray-600 block">
                {{
                  uploadedFrontCard
                    ? "身份证人像面已上传"
                    : "点击上传身份证正面"
                }}
              </text>
              <text class="text-[22rpx] text-gray-500 mt-[15rpx] block">
                {{
                  uploadedFrontCard
                    ? "点击可重新上传"
                    : "请确保身份证信息清晰可见"
                }}
              </text>
            </view>
            <!-- 显示身份证图片 -->
            <view
              v-else="uploadedFrontCard"
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
            >
              <img :src="getFullPath(formData.frontPic)" />
            </view>
          </view>

          <!-- 上传国徽面 -->
          <view class="mb-[40rpx]">
            <text
              class="block text-[28rpx] font-medium text-gray-700 mb-[15rpx]"
            >
              上传反面身份证 <text class="text-red-500">*</text>
            </text>
            <view
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
              :class="
                uploadedBackCard
                  ? 'border-blue-600 bg-white'
                  : 'hover:border-blue-600 hover:bg-white'
              "
              v-if="!uploadedBackCard"
              @click="uploadIdCard('back')"
            >
              <IconFont
                font-class-name="iconfont"
                class-prefix="icon"
                :name="uploadedBackCard ? 'file-image' : 'shenfenzhengfanmian2'"
                class="text-[50rpx] mb-[20rpx]"
                :class="uploadedBackCard ? 'text-green-500' : 'text-blue-600'"
                size="50"
                color="#4a6bff"
              />
              <text class="text-[26rpx] text-gray-600 block">
                {{ uploadedBackCard ? "身份证已上传" : "点击上传身份证反面" }}
              </text>
              <text class="text-[22rpx] text-gray-500 mt-[15rpx] block">
                {{
                  uploadedBackCard
                    ? "点击可重新上传"
                    : "请确保身份证信息清晰可见"
                }}
              </text>
            </view>
            <!-- 显示身份证图片 -->
            <view
              v-else="uploadedBackCard"
              class="border-2 border-dashed border-gray-200 rounded-[15rpx] p-[40rpx] text-center bg-gray-50 cursor-pointer transition-all"
            >
              <img :src="getFullPath(formData.backPic)" />
            </view>
          </view>

          <!-- 押金说明 -->
          <view class="bg-blue-50 rounded-[15rpx] p-[30rpx] mb-[40rpx]">
            <view class="text-[28rpx] font-semibold mb-[15rpx] text-blue-600">
              <text class="mr-1">🔸</text>
              <text>押金规则说明</text>
            </view>
            <view class="text-[24rpx] leading-[1.8]">
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text
                  >需缴纳平台保证金：<text class="font-bold">¥5,000</text></text
                >
              </view>
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>审核不通过时，押金将在3-5个工作日内原路退回</text>
              </view>
              <view class="mb-[10rpx] ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>合作期间如无违规行为，保证金在退出平台时全额退还</text>
              </view>
              <view class="ml-[30rpx] relative">
                <text class="absolute left-[-20rpx]">•</text>
                <text>保证金用于保障平台用户权益和服务质量</text>
              </view>
            </view>
          </view>
        </nut-form>
      </view>

      <!-- 提交按钮 -->
      <nut-button
        type="primary"
        size="large"
        class="w-full text-[32rpx] font-semibold bg-gradient-to-r from-blue-600 to-purple-600 h-[96rpx]"
        @click="handleSubmit"
      >
        提交审核
      </nut-button>
    </view>

    <!-- Footer -->
    <!-- <view class="text-center p-[30rpx] text-gray-500 text-[24rpx]">
      <text>© 2023 平台商家入驻中心 | 客服电话: 400-888-8888</text>
    </view> -->
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post, getFullPath } from "@/utils/request";
import PageHeader from "@/components/PageHeader.vue";

getIndustryText();
getMerchantTypeText();

interface IndustryColumn {
  update_time: null | number;
  create_time: number;
  img_url: null;
  name: string;
  description: string;
  id: number;
}

interface IndustryItem {
  columns: IndustryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface merchantTypes {
  columns: IndustryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

export interface Request {
  // 反面证件
  backPic?: string;
  // 正面证件
  frontPic?: string;
  // id
  id?: number;
  // 行业
  industrys?: string[];
  // 分页查询 第几页
  pageNo?: number;
  // 分页查询 每页多少条
  pageSize?: number;
  // 用户名
  realName?: string;
  // 证件编号
  realNo?: string;
  // 营业执照
  businessPic?: string;
  // 服务范围
  serviceScope?: string[];
  // 商家类型
  type?: string;
  agreeTerms?: boolean;
  [property: string]: any;
}

// 表单数据
const formData = ref<Request>({});

// 步骤
const steps = ref([
  { title: "选择类型", icon: "service-provider_fill", active: true },
  { title: "填写资料", icon: "file-alt", active: false },
  { title: "完成提交", icon: "check-circle", active: false },
]);

// 商家类型
const merchantTypes = ref([
  {
    value: "",
    name: "",
    desc: "提供专业服务解决方案",
    icon: "canyin",
  },
  {
    value: "",
    name: "",
    desc: "提供专业培训与指导",
    icon: "peixunguanli",
  },
  {
    value: "",
    name: "",
    desc: "传统文化与技艺传承",
    icon: "a-xintuobeifen2",
  },
  {
    value: "",
    name: "",
    desc: "提供优质产品与货源",
    icon: "gongyingshang",
  },
]);
// 商家类型列表
function getMerchantTypeText() {
  post("/dictionary/merchantType").then((res) => {
    console.log("==>", res.data);
    merchantTypes.value = res.data.map((item: merchantTypes) => ({
      name: item.columns.name,
      value: item.columns.id.toString(),
    }));
  });
}

// 选择商家类型
const selectType = (type: string) => {
  console.log(type);
  selectedType.value = type;
  // 保存商家类型
  formData.value.type = type;
};

// 行业相关
const industryOptions = ref<{ text: string; value: number }[]>([]);
const industryValue = ref<string[]>([]);
// 修改行业选择相关状态
const showIndustryPicker = ref(false);
const selectedIndustries = ref<number[]>([]); // 存储选中的行业ID
const industryText = ref('');

// 获取行业列表
function getIndustryText() {
  post("/dictionary/industry").then((res) => {
    industryOptions.value = res.data.map((item: IndustryItem) => ({
      text: item.columns.name,
      value: item.columns.id,
    }));
  });
}

// 处理行业选择确认
function onIndustryConfirm() {
  showIndustryPicker.value = false;
  
  // 生成行业名称文本
  const selectedNames = industryOptions.value
    .filter(item => selectedIndustries.value.includes(item.value))
    .map(item => item.text);
  
  industryText.value = selectedNames.join('、');
  
  // 保存行业ID数组
  formData.value.industrys = selectedIndustries.value;
}

// 切换行业选择状态
function toggleIndustry(id: number) {
  const index = selectedIndustries.value.indexOf(id);
  if (index > -1) {
    selectedIndustries.value.splice(index, 1);
  } else {
    selectedIndustries.value.push(id);
  }
}

// 上传状态
const selectedType = ref("training");
const uploadedLicense = ref(false);
const uploadedFrontCard = ref(false);
const uploadedBackCard = ref(false);


// 上传营业执照
const uploadLicense = () => {
  Taro.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      console.log(res);
      Taro.showLoading({ title: "上传中..." });
      const uploadRes = await Taro.uploadFile({
        url: "/file/upload",
        filePath: res.tempFilePaths[0],
        name: "file",
        header: {
          token: Taro.getStorageSync("token"),
        },
      });
      Taro.hideLoading();
      const data = JSON.parse(uploadRes.data);
      // 保存url地址
      formData.value.businessPic = data.data;
      uploadedLicense.value = true;
      Taro.showToast({
        title: "营业执照上传成功",
        icon: "success",
      });
    },
  });
};

// 上传身份证
const uploadIdCard = (pic: string) => {
  // 上传逻辑
  Taro.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: async (res) => {
      // console.log(res);
      Taro.showLoading({ title: "上传中..." });
      const uploadRes = await Taro.uploadFile({
        url: "/file/upload",
        filePath: res.tempFilePaths[0],
        name: "file",
        header: {
          token: Taro.getStorageSync("token"),
        },
      });
      Taro.hideLoading();
      const data = JSON.parse(uploadRes.data);
      if (pic == "front") {
        // 保存url地址
        formData.value.frontPic = data.data;
        // console.log("正面===>", getFullPath(formData.value.frontPic));
        uploadedFrontCard.value = true;
        Taro.showToast({
          title: "身份证反面上传成功",
          icon: "success",
        });
      } else {
        // 保存url地址
        formData.value.backPic = data.data;
        // console.log("反面===>", getFullPath(formData.value.backPic));
        uploadedBackCard.value = true;
        Taro.showToast({
          title: "身份证反面上传成功",
          icon: "success",
        });
      }
    },
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formData.value.industrys) {
    Taro.showToast({
      title: "请选择所属行业",
      icon: "none",
    });
    return;
  }

  if (!formData.value.serviceScope) {
    Taro.showToast({
      title: "请填写服务范围",
      icon: "none",
    });
    return;
  }

  if (!uploadedLicense.value) {
    Taro.showToast({
      title: "请上传营业执照",
      icon: "none",
    });
    return;
  }

  if (!uploadedFrontCard.value) {
    Taro.showToast({
      title: "请上传正面身份证",
      icon: "none",
    });
    return;
  }
  if (!uploadedBackCard.value) {
    Taro.showToast({
      title: "请上传反面身份证",
      icon: "none",
    });
    return;
  }

  // API接口
  const res = await post("/user/merchantAuthentication", formData.value);
  console.log("商家认证===>", res);
  if (res.code == "0") {
    Taro.showToast({
      title:
        "提交成功！\n您的申请已进入审核流程，我们将在3-5个工作日内完成审核。",
      icon: "success",
      duration: 3000,
    });
  }
};

// 返回上一页
const goBack = () => {
  Taro.navigateBack({
    delta: 1,
  });
};

</script>

<style lang="scss">
.bgs {
  .nut-cell-group__wrap {
    box-shadow: none !important;
  }
  .nut-textarea {
    padding: 0 !important;
  }
}
</style>
